import axios from 'axios'
import modal from 'ant-design-vue/lib/modal'
import message from 'ant-design-vue/lib/message'

import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import router from '@/router'
// 使用create方法创建axios实例
export const request = axios.create({
  timeout: 10000, // 请求超时时间,
  // headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
  baseURL: ''
})
// 添加请求拦截器
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  if (token) {
    config.headers[ACCESS_TOKEN] = token
  } else {
    delete config.headers[ACCESS_TOKEN]
  }
  return config
})
// 添加响应拦截器
request.interceptors.response.use(response => {
  const data = response.data || {}
  if (data.code && data.code !== 1) {
    if (data.code === 0) {
      message.error(data.msg || '操作失败')
    } else {
      const url = response.config.url
      if (url.indexOf('/admin/info') < 0) {
        /* info 接口的处理在 permission.js里 */
        modal.confirm({
          title: '登录超时，是否立即重新登录?',
          // content: h => <div style="color:red;">Some descriptions</div>,
          okText: '确定',
          cancelText: '取消',
          onOk () {
            router.push('/user/login')
          },
          onCancel () {
          }
        })
      }
    }
  }
  return data
}, error => {
  let msg = '请求出错'
  let code = 500
  if (error.response) {
    const res = error.response
    code = res.status
    if (res.status === 500) {
      msg = '内部服务错误' + res.data.msg
    } else if (res.status === 404) {
      msg = '接口不存在'
      if (res.data.path) {
        msg += (res.data.path || '')
      }
    }
  } else {
    if (error.message) {
      msg = error.message
    }
  }
  modal.error({
    title: '出错了，请联系管理员',
    content: msg
  })
  return Promise.resolve({
    code: code,
    msg: msg
  })
  // return Promise.reject(error)
})
